package com.wujilee.wujileenetty.demos.web.netty.heima;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;


/**
 * @author liwuji
 * @date 2024/8/15
 * @desc
 **/
@Slf4j
public class HttpDemoService {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();

        EventLoopGroup worker = new NioEventLoopGroup(10);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // http 编码和解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                @Override
                                protected void messageReceived(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                                    System.out.println(msg);
                                }


                            });
                        }
                    });
            ChannelFuture bind = serverBootstrap.bind(8080);
            // 该方法为阻塞方法
            ChannelFuture sync = bind.sync();
            sync.channel().closeFuture().sync();

        }catch (Exception e){
            log.error(" e ", e);
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}
